package gx.web.controller;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

import gx.entity.Category;
import gx.entity.Manager;
import gx.entity.Purchase;
import gx.entity.PurchaseItem;
import gx.entity.Supplier;
import gx.entity.Warehouse;
import gx.entity.common.Page;
import gx.service.CategoryService;
import gx.service.ProductService;
import gx.service.PurchaseItemService;
import gx.service.PurchaseService;
import gx.service.SupplierService;
import gx.service.WarehouseService;
@Controller
@RequestMapping("/mng/trans")
public class TransController {

	@Autowired
	private CategoryService categoryService;
	private WarehouseService warehouseService;
	private ProductService productService;
	private PurchaseItemService purchaseItemService;
	private PurchaseService purchaseService;
	@Autowired
	private SupplierService supplierService;

//	
//	@RequestMapping("/list.jhtml")
//	public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
//			@RequestParam(name = "number", defaultValue = "1") int number) {
//		ModelAndView mav = new ModelAndView("/mng/trans/list");
//		//List<Purchase> list = purchaseService.findByStatus(size, number,2);
//		List<Purchase> list = purchaseService.findAll();
//		mav.addObject("purc",list);
//		//	
//	@RequestMapping("/list.jhtml")
//	public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
//			@RequestParam(name = "number", defaultValue = "1") int number) {
//		ModelAndView mav = new ModelAndView("/mng/trans/list");
//		//List<Purchase> list = purchaseService.findByStatus(size, number,2);
//		List<Purchase> list = purchaseService.findAll();
//		mav.addObject("purc",list);
//		return mav;
//	}return mav;
//	}
//	@RequestMapping("/list.jhtml")
//	public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
//			@RequestParam(name = "number", defaultValue = "1") int number) {
//		ModelAndView mav = new ModelAndView("/mng/trans/list");
//		Page<Purchase> page = purchaseService.findByStatus(size, number, 0, 1,2,3);
//		mav.addObject("page", page);
//		return mav;
//	}
	// 根据ID修改
		@RequestMapping("/list.jhtml")
		public ModelAndView list() throws Exception {
			ModelAndView mav = new ModelAndView("/mng/ware/list");
			List<Warehouse> list = warehouseService.findAll();
			mav.addObject("list", list);
			return mav;
		}
	
//	@RequestMapping("/list.jhtml")
//	public ModelAndView list() throws Exception {
//		ModelAndView mav = new ModelAndView("/mng/ware/list");
//		List<Warehouse> list = warehouseService.findAll();
//		mav.addObject("list", list);
//		return mav;
//	}
	// 预加载添加页面数据
		@RequestMapping("/toAdd.jhtml")
		public ModelAndView toAdd() {
			ModelAndView mav = new ModelAndView("/mng/trans/add");
			// 供应商
			List<Supplier> supList = supplierService.findAll();
			mav.addObject("supList", supList);

			// 商品分类
			List<Category> cateList = categoryService.findAll();
			mav.addObject("cateList", cateList);

			// sn序列号
			StringBuffer sb = new StringBuffer("CG");
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			mav.addObject("sn", sb.append(sdf.format(date)).toString());

			return mav;
		}

	
	
		// 动态查询
		@RequestMapping("/find.jhtml")
		public ModelAndView find(@RequestParam(name = "size", defaultValue = "10") int size,
				@RequestParam(name = "number", defaultValue = "1") int number, Integer status, String startDate,
				String endDate) throws ParseException {
			// 离线查询条件对象 "from Purchase"
			DetachedCriteria dc = DetachedCriteria.forClass(Purchase.class);
			DetachedCriteria dc2 = DetachedCriteria.forClass(Purchase.class);
			DetachedCriteria dc3 = DetachedCriteria.forClass(Purchase.class);
			// "from Purchase where status?"
			if (status != null && status.intValue() >= 0) {
				dc.add(Property.forName("status").eq(status)); // eq: 等于
				dc2.add(Property.forName("status").eq(status));
				dc3.add(Property.forName("status").eq(status));
			} else {
				Criterion c = Restrictions.or(Restrictions.eq("status", 0), Restrictions.eq("status", 1));
				dc.add(c);
				dc2.add(c);
				dc3.add(c);
			}
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

			// "from Purchase where status=? and pur_date>? "
			if (null != startDate && !"".equals(startDate)) {
				dc.add(Property.forName("pur_date").ge(df.parse(startDate)));// ge:大于等于
				dc2.add(Property.forName("pur_date").ge(df.parse(startDate)));
				dc3.add(Property.forName("pur_date").ge(df.parse(startDate)));
			}

			// "from Purchase where status=? and pur_date>? and pur_date<?"
			if (null != endDate && !"".equals(endDate)) {
				dc.add(Property.forName("pur_date").le(df.parse(endDate)));// le:
																			// 小于等于
				dc2.add(Property.forName("pur_date").ge(df.parse(startDate)));
				dc3.add(Property.forName("pur_date").ge(df.parse(startDate)));
			}

			dc.addOrder(Order.desc("id"));
			dc2.setProjection(Projections.count("id"));
			dc3.setProjection(Projections.count("id"));

			Page<Purchase> page = purchaseService.findByCriteria(size, number, dc, dc2,dc3);

			ModelAndView mav = new ModelAndView("/mng/purc/list");
			mav.addObject("page", page);

			return mav;
		}

		// 编辑加载数据功能
		@RequestMapping("/detail.jhtml")
		public ModelAndView detail(Integer id) {
			ModelAndView mav = new ModelAndView("/mng/trans/detail");
			// 获得采购订单
			Purchase purchase = purchaseService.get(id);

			// 采购订单编号
			mav.addObject("sn", purchase.getSn());

			// 供应商
			List<Supplier> supList = supplierService.findAll();
			mav.addObject("supList", supList);

			// 商品分类
			List<Category> cateList = categoryService.findAll();
			mav.addObject("cateList", cateList);

			mav.addObject("purchase",purchase);
			
			mav.addObject("pur_list",purchase.getItemList());//采购项List
			return mav;
		}
		
		//修改功能
	    @RequestMapping("/edit.jhtml")
	    public String edit(int id,int pay_type, String pur_date, String remark, String sn, 
				Integer supp_id, Integer[] p_id,Integer[] p_num,
				BigDecimal[] sale_price, HttpSession session) throws ParseException{
	    	Manager mgr = (Manager) session.getAttribute("curr_mgr"); // 制单人信息

			Purchase purc = purchaseService.get(id); // 或得采购订单项
			purc.setManager(mgr); //制单人
			purc.setPay_type(pay_type); // 支付类型 0:全款 1:欠款
			if (pur_date != null && !"".equals(pur_date)) {
				purc.setPur_date(new SimpleDateFormat("yyyy-MM-dd").parse(pur_date));
			}
			purc.setRemark(remark); // 备注
			purc.setSn(sn); // 采购订单编号
			purc.setStatus(0); // 默认为草稿
			purc.setSupplier(supplierService.load(supp_id)); // 设置所属的供应商

			// 采购项
			ArrayList<PurchaseItem> items = new ArrayList<PurchaseItem>();

			//通过id查询所以采购订单项
			List<PurchaseItem> puritem_list = purchaseItemService.findByPurId(id);
			
			for(int i = 0; i < puritem_list.size();i++){
				
				purchaseItemService.delete(puritem_list.get(i));
				
			}
			int length = p_id == null ? 0 : p_id.length; // 采购订单项
			for (int i = 0; i < length; i++) {
				//删除
				Integer pitem_id = p_id[i];
				PurchaseItem item = new PurchaseItem(); // 采购订单项对象
				item.setNum(p_num[i]); // 数据
				item.setPrice(sale_price[i]); // 价格
				item.setProduct(productService.load(pitem_id)); // 设置所属商品
				item.setPurchase(purc); // 隶属采购订单

				boolean exists = false;
				for (PurchaseItem temp : items) {
					if (pitem_id.intValue() == temp.getProduct().getId().intValue()) {
						temp.setNum(temp.getNum() + p_num[i]);
						exists = true;
						break;
					}
				}

				if (!exists) {
					items.add(item);
				}
			}
			purc.setItemList(items);
			// 计算总价
			BigDecimal totals = new BigDecimal(0);
			for (PurchaseItem temp : items) {
				totals = totals.add(temp.getPrice().multiply(new BigDecimal(temp.getNum())));
			}
			purc.setCost(totals); // 采购订单中总额
			purchaseService.update(purc);
	       return "redirect:/mng/purc/list.jhtml";
	    }
		

	
}
